﻿using MoolinkHsmsServer;
using SuperSocket;
using SuperSocket.WebSocket;

using SuperSocket.SessionContainer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.WebSocket.Server;

namespace superSocketApi.Global
{
	public static class ServerInfoFun
	{
		public class SessionModel
		{
			public string DeviceId { get; set; }
			public string DeviceType { get; set; }
			public string SessionId { get; set; }
			public string WebSocket { get; set; }
			public string RemoteIp { get; set; }
			public int RemotePort { get; set; }
			//public string RemoteEndPoint { get { return RemoteIp + ":" + RemotePort.ToString(); } }
			public string LastActiveTime { get; set; }
		}
		public static List<SessionModel> SessionList1()
		{
			List<SessionModel> list = new List<SessionModel>();
			if (GlobalSystem.theHost!= null && GlobalSystem.theHost.AsServer().GetSessionContainer() != null && GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				foreach (var item in GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions())
				{
					//list.Add((item.RemoteEndPoint as IPEndPoint).Address.ToString() + "," + item.SessionID + "," + item["DeviceId"] + "," + item.DataContext + "," + item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss"));
					list.Add(new SessionModel
					{
						DeviceId = item["DeviceId"].ToString(),
						DeviceType = item["DeviceType"].ToString(),
						WebSocket= (item["WebSocket"]!=null)?(item["WebSocket"] as WebSocketSession).SessionID:"",
						SessionId = item.SessionID,
						RemoteIp = (item.RemoteEndPoint as IPEndPoint).Address.ToString(),
						RemotePort = (item.RemoteEndPoint as IPEndPoint).Port,
						LastActiveTime = item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss")
					});
					//item.SendAsync(Encoding.UTF8.GetBytes("hello," + item.SessionID));
				}
			}

			return list;
		}
		//public static List<SessionModel> SessionList2()
		//{
		//	List<SessionModel> list = new List<SessionModel>();
		//	if (GlobalSystem.server2!=null)
		//	{
		//		ISessionContainer _sessionContainer = GlobalSystem.server2.GetSessionContainer();
		//		if (_sessionContainer == null) Console.Write(GlobalSystem.server2.SessionCount.ToString());
		//		//foreach (var item in GlobalSystem.server2.GetSessionContainer().GetSessions())
		//		//{
		//		//	//list.Add((item.RemoteEndPoint as IPEndPoint).Address.ToString() + "," + item.SessionID + "," + item["DeviceId"] + "," + item.DataContext + "," + item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss"));
		//		//	list.Add(new SessionModel
		//		//	{
		//		//		DeviceId = item["DeviceId"].ToString(),
		//		//		SessionId = item.SessionID,
		//		//		RemoteIp = (item.RemoteEndPoint as IPEndPoint).Address.ToString(),
		//		//		RemotePort = (item.RemoteEndPoint as IPEndPoint).Port,
		//		//		LastActiveTime = item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss")
		//		//	});
		//		//	//item.SendAsync(Encoding.UTF8.GetBytes("hello," + item.SessionID));
		//		//}
		//	}

		//	return list;
		//}

		public static List<SessionModel> WebSocketSessionList()
		{
			List<SessionModel> list = new List<SessionModel>();
			if (GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				foreach (var item in GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions())
				{
					//list.Add((item.RemoteEndPoint as IPEndPoint).Address.ToString() + "," + item.SessionID + "," + item["DeviceId"] + "," + item.DataContext + "," + item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss"));
					list.Add(new SessionModel
					{
						DeviceId = item["DeviceId"].ToString(),
						SessionId = item.SessionID,
						RemoteIp = (item.RemoteEndPoint as IPEndPoint).Address.ToString(),
						RemotePort = (item.RemoteEndPoint as IPEndPoint).Port,
						LastActiveTime = item.LastActiveTime.ToString("yyyy-MM-dd HH:mm:ss")
					});
					//item.SendAsync(Encoding.UTF8.GetBytes("hello," + item.SessionID));
				}
			}

			return list;
		}



		public static string SendHsmsDataBySessionId(string sessionId, byte stream, byte function, string bodyData, bool reply = true,bool waitreply=true)
		{
			int MaxWait = 50; //等待回复超时5秒
			byte[] bytes = bodyData.HexStringGetByteArray();
			HsmsMessage msg = new HsmsMessage();
			msg.HeaderFrame.DeviceId = 0;
			msg.HeaderFrame.Stream = stream;
			msg.HeaderFrame.Function = function;
			msg.HeaderFrame.Reply = reply;
			msg.HeaderFrame.Ptype = 0;
			msg.HeaderFrame.Stype = 0;

			//if (bytes.Length >= 14)
			//{
			//	Array.Copy(bytes, 4, msg.HeaderFrame.Bytes, 0, 10);
			//	if (bytes.Length > 14)
			//	{
			//		msg.TextFrame.Bytes = new byte[bytes.Length - 14];
			//		Array.Copy(bytes, 14, msg.TextFrame.Bytes, 0, bytes.Length - 14);
			//	}
			//}
			if (bytes != null && bytes.Length > 0)
			{
				msg.TextFrame.Bytes = new byte[bytes.Length];
				Array.Copy(bytes, 0, msg.TextFrame.Bytes, 0, bytes.Length);
			}

			msg.RefreshLengthByte();
			msg.RefreshSystemByte();


			if (GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				IAppSession s = GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessionByID(sessionId);
				if (s != null && s.State == SessionState.Connected)
				{
					msg.HeaderFrame.DeviceId = Convert.ToUInt16(s["DeviceId"]);
					s["ApiReqId"]= msg.HeaderFrame.SystemByte;
					s.SendAsync(msg.GetByteArray());

					if(reply==false||waitreply == false) return msg.ToJson();

					while (((HsmsMessage)s.DataContext).HeaderFrame.SystemByte != msg.HeaderFrame.SystemByte)
					{
						Thread.Sleep(100);
						if (MaxWait > 0) MaxWait--; else { msg.HeaderFrame.SystemByte = 0; return msg.ToJson(); }
					}
					//if (((HsmsMessage)s.DataContext).HeaderFrame.SystemByte == msg.HeaderFrame.SystemByte) return ((HsmsMessage)s.DataContext);
					return ((HsmsMessage)s.DataContext).ToJson();

				}
			}




			msg.HeaderFrame.SystemByte = 0;
			return msg.ToJson();

		}
		public static HsmsMessage SendHsmsCmdBySessionId(string sessionId, byte stype, bool reply = false)
		{
			int MaxWait = 50; //等待回复超时5秒
			if (stype == 1 || stype == 3 || stype == 5) reply = true;
			HsmsMessage msg = new HsmsMessage();
			msg.HeaderFrame.DeviceId = 0;
			msg.HeaderFrame.Stream = 0;
			msg.HeaderFrame.Function = 0;
			msg.HeaderFrame.Reply = reply;
			msg.HeaderFrame.Ptype = 0;
			msg.HeaderFrame.Stype = stype;


			msg.RefreshLengthByte();
			msg.RefreshSystemByte();


			if (GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				IAppSession s = GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessionByID(sessionId);
				if (s != null && s.State == SessionState.Connected)
				{
					msg.HeaderFrame.DeviceId = Convert.ToUInt16(s["DeviceId"]);
					s["ApiReqId"] = msg.HeaderFrame.SystemByte;
					s.SendAsync(msg.GetByteArray());

					if(msg.HeaderFrame.Reply==false) { msg.HeaderFrame.SystemByte = 0; return msg; }

					while (((HsmsMessage)s.DataContext).HeaderFrame.SystemByte != msg.HeaderFrame.SystemByte)
					{
						Thread.Sleep(100);
						if (MaxWait > 0) MaxWait--; else { msg.HeaderFrame.SystemByte = 0; return msg; }
					}
					//if (((HsmsMessage)s.DataContext).HeaderFrame.SystemByte == msg.HeaderFrame.SystemByte) return ((HsmsMessage)s.DataContext);
					return ((HsmsMessage)s.DataContext);

				}
			}

			msg.HeaderFrame.SystemByte = 0;
			return msg;

		}


		public static string SendHexDataBySessionId(string sessionId, string bodyData)
		{

			if (GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				IAppSession s = GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessionByID(sessionId);
				if (s != null && s.State == SessionState.Connected) s.SendAsync(bodyData.HexStringGetByteArray());
			}

			return bodyData;

		}

		public static string SendStringBySessionId(string sessionId, string sendData)
		{

			if (GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				IAppSession s = GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessionByID(sessionId);
				if (s != null && s.State == SessionState.Connected) s.SendAsync(Encoding.UTF8.GetBytes(sendData));
			}

			return "[]";

		}

		public static string SendHexBySessionId(string sessionId, string sendData)
		{
			byte[] bytes = sendData.HexStringGetByteArray();

			if (bytes!=null&&GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessions() != null)
			{
				IAppSession s = GlobalSystem.theHost.AsServer().GetSessionContainer().GetSessionByID(sessionId);
				if (s != null && s.State == SessionState.Connected) s.SendAsync(bytes);
			}

			return "[]";

		}




	}
}
